<%@ page contentType="text/html;charset=UTF-8"%>
<%@ page import="cn.org.rapid_framework.web.scope.Flash"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<c:if test="${flash.error != null}">
<script type="text/javascript">
	layer.msg('${flash.error}',{icon:2,area:'100px'})
</script>
</c:if>

<c:if test="${flash.success != null}">
<script type="text/javascript">
    var msg = "${flash.success}";
	layer.msg(msg,{icon:1,area:'100px'});
</script>
</c:if>

<script>

	//日期空间
	
	/*常量*/
var CONSTANT = {
        DATA_TABLES : {
            DEFAULT_OPTION : { //DataTables初始化选项
                language: {
                    "sProcessing":   "处理中...",
                    "sLengthMenu":   "每页 _MENU_ 项",
                    "sZeroRecords":  "没有匹配结果",
                    "sInfo":         "当前显示第 _START_ 至 _END_ 项，共 _TOTAL_ 项。",
                    "sInfoEmpty":    "当前显示第 0 至 0 项，共 0 项",
                    "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                    "sInfoPostFix":  "",
                    "sSearch":       "搜索:",
                    "sUrl":          "",
                    "sEmptyTable":     "表中数据为空",
                    "sLoadingRecords": "载入中...",
                    "sInfoThousands":  ",",
                    "oPaginate": {
                        "sFirst":    "首页",
                        "sPrevious": "上页",
                        "sNext":     "下页",
                        "sLast":     "末页",
                        "sJump":     "跳转"
                    },
                    "oAria": {
                        "sSortAscending":  ": 以升序排列此列",
                        "sSortDescending": ": 以降序排列此列"
                    }
                },
                autoWidth: false,   //禁用自动调整列宽
                stripeClasses: ["odd", "even"],//为奇偶行加上样式，兼容不支持CSS伪类的场合
                order: [],          //取消默认排序查询,否则复选框一列会出现小箭头
                processing: false,  //隐藏加载提示,自行处理
                serverSide: true,   //启用服务器端分页
                searching: false ,   //禁用原生搜索
                pagingType:   "full_numbers",
                dom: 'rt<"bottom"pil><"clear">',
            },
            COLUMN: {
                CHECKBOX: { //复选框单元格
                    className: "td-checkbox",
                    orderable: false,
                    width: "30px",
                    data: null,
                    render: function (data, type, row, meta) {
                        return '<input type="checkbox" class="iCheck">';
                    }
                }
            },
            RENDER: {   //常用render可以抽取出来，如日期时间、头像等
                ELLIPSIS: function (data, type, row, meta) {
                    data = data||"";
                    return '<span title="' + data + '">' + data + '</span>';
                }
            }
        }
	};
var _table;
function createDataTable(createColumns, getParams){
	var $wrapper = $('#div-table-container');
	var $table = $('#table-user');

	_table = $table.dataTable($.extend(true,{},CONSTANT.DATA_TABLES.DEFAULT_OPTION, {
	    ajax : function(data, callback, settings) {//ajax配置为function,手动调用异步查询
	        //手动控制遮罩
//	         $wrapper.spinModal();
	        //封装请求参数
	        var param = getParams();
	        var queryData = param.data;
	        queryData.pageNumber = data.start / data.length + 1;
	        queryData.pageSize = data.length;
	        if(data.order.length > 0){
	        	queryData.sortColumns = data.columns[data.order[0].column].name + ' ' + data.order[0].dir
	        }
	        var loadingIndex = layer.load(2, {shade: [0.4,'#000'] });
	        $.ajax({
	                type: "GET",
	                url: param.url,
	                cache : false,  //禁用缓存
	                data: queryData,    //传入已封装的参数
	                dataType: "json",
	                success: function(result) {
	                		layer.close(loadingIndex);
	                        if (result.errorCode) {
	                            layer.msg("查询失败。错误码：" + result.errorCode,{icon:2})
	                            return;
	                        }
	                        //封装返回数据，这里仅演示了修改属性名
	                        var returnData = {};
	                        returnData.draw = data.pageNumber;
	                        returnData.recordsTotal = result.totalCount;
	                        returnData.recordsFiltered = result.totalCount;
	                        returnData.data = result.result;
	                        callback(returnData);
	                },
	                error: function(XMLHttpRequest, textStatus, errorThrown) {
	                    console.log(XMLHttpRequest);
	                    console.log(textStatus);
	                    console.log(errorThrown);
	                	layer.closeAll('loading');
	                	if(XMLHttpRequest.status == 401){
                            layer.msg(XMLHttpRequest.responseText,{icon:2});
                        }else{
                            layer.msg('查询失败',{icon:2});
                        }

	                }
	            });
	    },
	    columns: createColumns(),
	    "createdRow": function ( row, data, index ) {
	        //行渲染回调,在这里可以对该行dom元素进行任何操作
	        //给当前行加样式
	        if (data.role) {
	            $(row).addClass("info");
	        }
	        //给当前行某列加样式
//	         $('td', row).eq(3).addClass(data.status?"text-success":"text-error");
	        //不使用render，改用jquery文档操作呈现单元格
//	         var $btnEdit = $('<button type="button" class="btn btn-small btn-primary btn-edit">修改</button>');
//	         var $btnDel = $('<button type="button" class="btn btn-small btn-danger btn-del">删除</button>');
//	         $('td', row).eq(5).append($btnEdit).append($btnDel);

	    },
	    "drawCallback": function( settings ) {
	        //渲染完毕后的回调
	        //清空全选状态
            $(":checkbox[name='cb-check-all']").parent().attr("style", "width:5px");
	        $(":checkbox[name='cb-check-all']",$wrapper).prop('checked', false);
            $('#div-table-container').append($('#div-table-container').find('.bottom'));
            bindMoneyClass();
	    }
		})).api();
	return _table;
}	
	
	function dosearch(){
		_table.ajax.reload();
	}
	
	function clearFilters(){
		$('.input-fillter').val("");
	}
	
	function bindMoneyClass(){
		var tds = $('.money.money-profit');
		for(var i = 0;i<tds.length;i++){
			var td = $(tds[i]);
			var tdText = td.text();
			var n = new Number(tdText);
			if(!isNaN(n)){
				if(n>=0){
					td.addClass('money-add');
				}else{
					td.addClass('money-minus');
				}
			}
		}
	}

	$('.datetimerange-btn').daterangepicker(
			{
				// startDate: moment().startOf('day'),
				//endDate: moment(),
				//minDate: '01/01/2012',    //最小时间
				maxDate : moment(), //最大时间
				dateLimit : {
					days : 90
				},
				showDropdowns : true,
				showWeekNumbers : false, //是否显示第几周
				timePicker : true, //是否显示小时和分钟
				timePickerIncrement : 60, //时间的增量，单位为分钟
				timePicker12Hour : false, //是否使用12小时制来显示时间
				ranges : {
					//'最近1小时': [moment().subtract('hours',1), moment()],
					'今日' : [ moment().startOf('day'), moment() ],
					'昨日' : [ moment().subtract('days', 1).startOf('day'),
							moment().subtract('days', 1).endOf('day') ],
					'最近7日' : [ moment().subtract('days', 6), moment() ],
					'最近30日' : [ moment().subtract('days', 29), moment() ]
				},
				opens : 'right', //日期选择框的弹出位置
				format : 'YYYY-MM-DD HH:mm:ss', //控件中from和to 显示的日期格式
				separator : ' to ',
				locale : {
					applyLabel : '确定',
					cancelLabel : '取消',
					fromLabel : '起始时间',
					toLabel : '结束时间',
					customRangeLabel : '自定义',
					daysOfWeek : [ '日', '一', '二', '三', '四', '五', '六' ],
					monthNames : [ '一月', '二月', '三月', '四月', '五月', '六月', '七月',
							'八月', '九月', '十月', '十一月', '十二月' ],
					firstDay : 1
				}
			},
			function(start, end, label) {//格式化日期显示框
				var s = start.format('YY/MM/DD HH:mm') + ' - '
						+ end.format('YY/MM/DD HH:mm');
				$(this.element).val(s);
			});

// 	$('.datetimepicker').datepicker({
// 		autoclose : true
// 	});
	
// 	window.setTimeout(function() {
//         $('.alert').alert('close');
//     }, 3000);


	function layerCheck(title, onresult,required1,required2){
		var content = '<div><div><textarea id="textarea-layer" style="min-height:150px" class="layui-layer-input form-control" placeholder="请填写备注"></textarea><div>'
			+'<div class="pull-right" style="margin-top:20px"><button class="btn btn-sm btn-success"  id="btn-layer-ok" style="margin-left:10px; min-width:80px">通 过</button>'
			+'<button class="btn btn-sm btn-danger" id="btn-layer-no" style="margin-left:20px; min-width:80px">拒 绝</button>'
			+'<button class="btn btn-sm btn-default" id="btn-layer-close" style="margin-left:20px; min-width:50px">取 消</button>'
			+'</div></div>';
			$content = $(content);
			var index = layer.open({
					title : title,
					closeBtn: 1,
					area : ["400px","300px"],
					content : content,
					shadeClose: true,
					btn :[],
					success : function(layero, index){
						var check = function(yes){
//		 					layer.close(index)
							var tx = $("#textarea-layer");
							var note = tx.val();
							if(note.length==0){
								if(yes && (required1==true) || !yes && (required2==true)){
									tx.focus();
									return;
								}
							}
							onresult(yes,note);
						} 
						$("#btn-layer-ok").click(function(){
							check(true)
						});
						$("#btn-layer-no").click(function(){
							check(false)
						});
						$("#btn-layer-close").click(function(){
							layer.close(index);
						});
					}
			});
	}
</script>